// test project main.go
package utils

import (
	"crypto/md5"
	"encoding/base64"
	"encoding/hex"
	"math/rand"
)

func reverse(s []byte) []byte {
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}

	return s
}

func Encrypt(key, data string) string {
	b := base64.StdEncoding.EncodeToString([]byte(data))

	array := []byte(b)

	array = reverse(array)

	sk := md5.Sum([]byte(key))

	k := reverse(sk[:])

	i := 0

	for index, element := range array {
		if i == len(k) {
			i = 0
		}

		xor := k[i]

		array[index] = element ^ xor

		i++
	}

	return base64.StdEncoding.EncodeToString(array)

}

func Decrypt(key, data string) (string, error) {
	array, error := base64.StdEncoding.DecodeString(data)

	if error != nil {
		return "", error
	}

	sk := md5.Sum([]byte(key))

	k := reverse(sk[:])

	i := 0

	for index, element := range array {
		if i == len(k) {
			i = 0
		}

		xor := k[i]

		array[index] = element ^ xor

		i++
	}

	array = reverse(array)

	b, error := base64.StdEncoding.DecodeString(string(array))

	return string(b), error

}

func RandString(length int) string {
	data := make([]byte, length)

	var num int

	for i := 0; i < length; i++ {
		num = rand.Intn(57) + 65

		for {
			if num > 90 && num < 97 {
				num = rand.Intn(57) + 65
			} else {
				break
			}
		}
		data[i] = byte(num)
	}
	return string(data)
}

func HexMD5(data string) string {
	tmp := md5.Sum([]byte(data))
	return hex.EncodeToString(tmp[:])
}
